<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/admin/news' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>敏感词管理</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="tag-list">
      <el-tag
        :key="tag.sensitiveId"
        v-for="tag in dynamicTags"
        closable
        :disable-transitions="false"
        @close="handleClose(tag)"
      >{{tag.sensitiveTag}}</el-tag>
      <el-input
        class="input-new-tag"
        v-if="inputVisible"
        v-model="inputValue"
        ref="saveTagInput"
        size="small"
        @keyup.enter.native="handleInputConfirm"
        @blur="handleInputConfirm"
      ></el-input>
      <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 添加</el-button>
    </div>
  </div>
</template>

<script>
import {
  sensitivesListAll,
  sensitivesSave,
  sensitivesDelete
} from "../../ajax/index";
export default {
  data() {
    return {
      dynamicTags: [],
      inputVisible: false,
      inputValue: ""
    };
  },
  created() {
    this.sensitivesListAll();
  },
  methods: {
    handleClose(tag) {
      sensitivesDelete({
        sensitiveId: tag.sensitiveId
      })
        .then(res => {
          if (res.code) {
            this.dynamicTags.splice(
              this.dynamicTags.findIndex(
                item => item.sensitiveId == tag.sensitiveId
              ),
              1
            );
          } else {
          }
        })
        .catch(err => {
          this.$message.error("删除失败，请稍后再试！");
        });
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      sensitivesSave({
        sensitiveTag: this.inputValue
      })
        .then(res => {
          if (res.code) {
            this.dynamicTags.push(res.data);
            this.inputVisible = false;
            this.inputValue = "";
          } else {
            this.$message({
              type: "info",
              message: res.msg
            });
          }
        })
        .catch(err => {
          this.editFormVisible = false;
          this.loading = false;
          this.$message.error("敏感词保存失败，请稍后再试！");
        });
    },

    sensitivesListAll() {
      sensitivesListAll()
        .then(res => {
          if (res.code) {
            this.dynamicTags = res.data;
          }
        })
        .catch(err => {
          this.loading = false;
          this.$message.error("标签加载失败，请稍后再试！");
        });
    }
  }
};
</script>

<style lang="scss" scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.tag-list {
  margin: 60px 30px;
}
</style>